package com.mall.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.commons.exceotion.BusinessException;
import com.mall.commons.exceotion.ErrorResult;
import com.mall.dubbo.mappers.ResourceCategoryMapper;
import com.mall.dubbo.mappers.UmsResourceMapper;
import com.tanhua.model.domain.UmsResource;
import com.tanhua.model.domain.UmsResourceCategory;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@DubboService
public class ResourceCategoryApiImpl implements ResourceCategoryApi {

    @Autowired
    private ResourceCategoryMapper resourceCategoryMapper;
    @Autowired
    private UmsResourceMapper umsResourceMapper;

    @Override
    public List<UmsResourceCategory> listAll() {
        LambdaQueryWrapper<UmsResourceCategory> queryWrapper = new LambdaQueryWrapper<>();
        return resourceCategoryMapper.selectList(queryWrapper);
    }

    /**
     * 根据ID删除后台资源
     *
     * @param id
     * @return
     */
    @Override
    public boolean deletes(Integer id) {
        if (id == null) {
            return false;
        }
        //去查UmsResource是否存在分类,有的话就不该删除
        LambdaQueryWrapper<UmsResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UmsResource::getCategoryId, id);
        Integer integer = umsResourceMapper.selectCount(wrapper);
        if (umsResourceMapper.selectCount(wrapper) > 0) {
            throw new BusinessException(ErrorResult.serveError());
        }
        return resourceCategoryMapper.deleteById(id) > 0 ? true : false;
    }

    /**
     * 添加后台资源分类
     *
     * @param umsResourceCategory
     * @return
     */
    @Override
    public boolean create(UmsResourceCategory umsResourceCategory) {
        if (umsResourceCategory != null) {

            LambdaQueryWrapper<UmsResourceCategory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UmsResourceCategory::getName, umsResourceCategory.getName());
            //名字重复直接抛
            if (resourceCategoryMapper.selectCount(wrapper) > 0) {
                throw new BusinessException(ErrorResult.resourceError());
            }
            umsResourceCategory.setCreateTime(new Date(System.currentTimeMillis()));
            return resourceCategoryMapper.insert(umsResourceCategory) > 0 ? true : false;
        }
        return false;
    }

    /**
     * 修改后台资源分类
     *
     * @param umsResourceCategory
     * @param id
     * @return
     */
    @Override
    public boolean updates(UmsResourceCategory umsResourceCategory, Integer id) {
        if (umsResourceCategory != null) {
            return resourceCategoryMapper.updateById(umsResourceCategory) > 0 ? true : false;
        }
        return false;
    }
}
